package com.chen.gcode.fx.controllers;

import com.chen.gcode.utils.GCodeGenerate;
import com.chen.gcode.utils.Setting;
import io.netty.util.internal.StringUtil;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.input.DragEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

public class WDGCodeController implements Initializable {

    @FXML
    private AnchorPane pane;
    @FXML
    private TextField pathTextFiled;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        pathTextFiled.setText(Setting.getInstance().getWdFilePath());
    }

    public void makeGCode(){

        String imagePath = pathTextFiled.getText().trim();


        if (StringUtil.isNullOrEmpty(imagePath)){
            JOptionPane.showMessageDialog(null, "请选图片");
            return;
        }


        File imageFile = new File(imagePath);


//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
//        String date = df.format(new Date());

        String savePath = Setting.getInstance().getSavePath().trim()+ File.separator+ imageFile.getName()+ ".nc";

        if (StringUtil.isNullOrEmpty(Setting.getInstance().getSavePath().trim())){
            JOptionPane.showMessageDialog(null, "请选保存路径");
            return;
        }

        GCodeGenerate gCodeGenerate = new GCodeGenerate();

        gCodeGenerate.changeCode(imagePath,savePath);
    }

    public void openDir(){
        File file = new File(Setting.getInstance().getSavePath().trim());
        try {
            if (file != null && file.exists())
                Desktop.getDesktop().open(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    public void chooseFile(ActionEvent e){


        FileChooser fileChooser=new FileChooser();
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图片类型", "*.nc"),
                new FileChooser.ExtensionFilter("所有类型", "*.*")
        );
        File file = fileChooser.showOpenDialog(pane.getScene().getWindow());
        String path = file.getPath();//选择的文件夹路径

        if (path != null){
            pathTextFiled.setText(path);
        }
    }

    @FXML
    void getFile(DragEvent event) {
        List<File> files = event.getDragboard().getFiles();
        //获得文件
        File file = files.get(0);
        //之后的相关操作，获得文件路径等..
        if (file != null){
            pathTextFiled.setText(file.getPath());
        }
    }
}
